package com.imu.chatmodule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imu.chatmodule.LongConnection.util.LongConnectionMsgUtil;
import com.imu.chatmodule.LongConnection.util.LongConnectionUtil;
import com.imu.chatmodule.ab.entity.Chatrecord;
import com.imu.chatmodule.ab.service.IChatrecordService;
import com.imu.chatmodule.service.IChatService;
import io.netty.channel.socket.SocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ChatServiceImpl implements IChatService {
    @Autowired
    IChatrecordService chatrecordService;


    @Override
    public boolean sendMessageById(String receiverId, byte[] bytes) {
        if (LongConnectionUtil.checkIdWhetherOnline(receiverId)) {
            SocketChannel socketChannel = LongConnectionUtil.getChannelById(receiverId);
            socketChannel.writeAndFlush(LongConnectionMsgUtil.bytesToByteBuf(bytes));
        }

        return false;
    }


    @Override
    public List<Chatrecord> getAllUnReadMsg(String id) {
        QueryWrapper<Chatrecord> wrapper = new QueryWrapper<>();
        wrapper.eq("if_read", "F").eq("receiver_id", id).select("receiver_id", "sender_id", "message", "msg_type", "rb", "CREATED_TIME", "msg_id").orderByAsc("CREATED_TIME");
        List<Chatrecord> list = chatrecordService.list(wrapper);
        return list;
    }


    @Override
    public List<Chatrecord> getAllFriendsThreeHistoryChats(String id) {
        QueryWrapper<Chatrecord> wrapper = new QueryWrapper<>();
        wrapper.eq("sender_id", id).select("receiver_id");
        List<Chatrecord> receiverList = chatrecordService.list(wrapper);
        wrapper.clear();
        wrapper.eq("receiver_id", id).select("sender_id");
        List<Chatrecord> senderList = chatrecordService.list(wrapper);

        Set<String> set = receiverList.stream().map(Chatrecord::getReceiverId).collect(Collectors.toSet());
        senderList.stream().map(Chatrecord::getReceiverId).forEach(set::add);
        //System.out.println(set);

        List<Chatrecord> rs = new ArrayList<>();
        for (String item :
                set) {
            Runnable runnable = () -> {
                QueryWrapper<Chatrecord> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("receiver_id", item).and(i -> i.eq("sender_id", id)).or().eq("sender_id", item).and(i -> i.eq("receiver_id", id)).
                        select("receiver_id", "sender_id", "message", "msg_type", "rb", "CREATED_TIME", "msg_id").orderByDesc("CREATED_TIME").last("limit 3");
                List<Chatrecord> list = chatrecordService.list(wrapper1);
                rs.addAll(list);
            };
            runnable.run();
        }
        return rs;
    }


    @Override
    public List<Chatrecord> getFiveHisChats(String msgId, String user1, String user2) {
        //System.out.println(user1 + "" + user2);
        LocalDateTime lastTime = chatrecordService.getById(msgId).getCreatedTime();
        QueryWrapper<Chatrecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiver_id", user1).and(i -> i.eq("sender_id", user2)).
                le("CREATED_TIME", lastTime).and(i -> i.ne("msg_id", msgId)).select("receiver_id", "sender_id", "message", "msg_type", "rb", "CREATED_TIME", "msg_id")
                .orderByDesc("CREATED_TIME").last("limit 5");
        List<Chatrecord> list = chatrecordService.list(queryWrapper);

        queryWrapper.clear();
        queryWrapper.eq("sender_id", user1).and(i -> i.eq("receiver_id", user2)).
                le("CREATED_TIME", lastTime).and(i -> i.ne("msg_id", msgId)).select("receiver_id", "sender_id", "message", "msg_type", "rb", "CREATED_TIME", "msg_id")
                .orderByDesc("CREATED_TIME").last("limit 5");

        list.addAll(chatrecordService.list(queryWrapper));
        //System.out.println(list);
        return list;
    }

    @Override
    public List<Chatrecord> getHisChatsBetweenDate(String Id, String Id2, LocalDateTime bg, LocalDateTime ed) {
        QueryWrapper<Chatrecord> wrapper = new QueryWrapper<>();
        wrapper.eq("sender_id", Id).and(i -> i.eq("receiver_id", Id2)).le("CREATED_TIME", ed).ge("CREATED_TIME", bg)
                .select("receiver_id", "sender_id", "message", "msg_type", "rb", "CREATED_TIME", "msg_id");
        List<Chatrecord> list = chatrecordService.list(wrapper);

        wrapper.clear();
        wrapper.eq("receiver_id", Id).and(i -> i.eq("sender_id", Id2)).le("CREATED_TIME", ed).ge("CREATED_TIME", bg)
                .select("receiver_id", "sender_id", "message", "msg_type", "rb", "CREATED_TIME", "msg_id");
        list.addAll(chatrecordService.list(wrapper));
        return list;
    }
}
